# coding: UTF-8
# Filename : chain_partactivity_api.py
# Company : imedia
# Author : zqz 
# -*-coding:utf-8 -*-
from api.common.common import *
from api.common import mysql,log,utils,httputils,const
import chain_partactivity_data_model
import time

#查询公共sql
common_sql = '''
SELECT name,category_id,start_time,end_time,images, 
store_in_app,description,class_name, b.id, b.summary
FROM chain_part_activity as a, chain_activity as b left JOIN p_class c  ON b.category_id = c.id 
where a.activity_id = b.id   
'''

#替换字符
def replace_body(obj):
    if obj == None : return ''
    #替换模板
    ISOTIMEFORMAT='%Y-%m-%d_%X'
    from_time = time.strftime(ISOTIMEFORMAT,time.localtime(obj[2]))
    end_time = time.strftime(ISOTIMEFORMAT,time.localtime(obj[3]))
    body_template = chain_partactivity_data_model.imedia_body
    body_template = body_template.replace('{name}', str(obj[0]))
    body_template = body_template.replace('{category_id}', str(obj[1]))
    body_template = body_template.replace('{from}', from_time)
    body_template = body_template.replace('{to}', end_time)
    body_template = body_template.replace('{image}', str(obj[4]))
    body_template = body_template.replace('{storeinapp}', str(obj[5]))
    body_template = body_template.replace('{description}', str(obj[6]))
    body_template = body_template.replace('{id}', str(obj[8]))
    body_template = body_template.replace('{category_name}', str(obj[7]))
    body_template = body_template.replace('{summary}', str(obj[9]))
    return body_template

#获取中间数据体
def get_body_str(part_id, size, pagenum):
    #sql
    sql = common_sql + '''
    and chain_part_id = %s
    and b.active = 1
    limit %s, %s
    '''
    #获取起始行
    start_row = utils.get_star_row(size, pagenum)
    param = [int(part_id), start_row, int(size)]
    rsts = mysql.doSearch(sql, param)
    body_str = ''
    for obj in rsts:
        body_str += replace_body(obj)
    return body_str

#获取详细列表http://api.imedia.com/app/partactivity/list
def chain_partactivity_list(request):
    #记录用户脚印(必做动作)
    httputils.footprint(request)
    #获取请求参数
    part_id = httputils.post(request, 'part_id')#分店id
    size = httputils.post(request, 'size')
    pagenum = httputils.post(request, 'pagenum')
    if not utils.is_num(size): size = 5
    if not utils.is_num(pagenum): pagenum = 1
    if not utils.is_num(part_id): part_id = 1
    #以下两参数必有
    if validate(request):
        return validate(request)
    #中间模板段
    output = chain_partactivity_data_model.imedia_start 
    output += get_body_str(part_id, size, pagenum)
    output += chain_partactivity_data_model.imedia_end
    return response(output)

